package team.seekers.skill.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import team.seekers.skill.common.utils.SkillUtils;
import team.seekers.skill.entity.dao.SkillComment;
import team.seekers.skill.entity.dao.Skill;
import team.seekers.skill.entity.dao.User;
import team.seekers.skill.entity.query.CommentQuery;
import team.seekers.skill.entity.vo.fore.add.SkillCommentAddVO;
import team.seekers.skill.entity.vo.fore.list.SkillCommentListVO;
import team.seekers.skill.entity.vo.fore.update.SkillCommentUpdateVO;
import team.seekers.skill.mapper.SkillCommentMapper;
import team.seekers.skill.service.SkillCommentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import team.seekers.skill.service.SkillService;
import team.seekers.skill.service.UserService;
import team.seekers.skill.common.utils.UserInfo;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hbc
 * @since 2021-01-18
 */
@Service
public class SkillCommentServiceImpl extends ServiceImpl<SkillCommentMapper, SkillComment> implements SkillCommentService {

    @Autowired
    private SkillService skillService;
    @Autowired
    private UserService userService;

    //用户渠道
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean add(SkillCommentAddVO commentVO) {
        SkillComment skillComment = new SkillComment();
        BeanUtils.copyProperties(commentVO, skillComment);
        skillComment.setUserId(SkillUtils.getUserId());
        boolean save = save(skillComment);
        if (!save)
            return false;
        else {
            //更新技能星级和评论数
            Skill skill = skillService.getById(commentVO.getSkillId());
            String oldStar = skill.getStar();
            Integer oldComments = skill.getComments();
            double newStar = (Double.parseDouble(oldStar)*oldComments+commentVO.getStar())/(oldComments+1);
            DecimalFormat df = new DecimalFormat("#.0");
            String star = df.format(newStar);
            skill.setStar(star);
            skill.setComments(oldComments+1);
            boolean update = skillService.updateById(skill);
            if (!update)
                return false;
            return true;
        }
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean delete(String commentId) {
        SkillComment skillComment = getById(commentId);
        // 权限判断
        if (!skillComment.getUserId().equals(SkillUtils.getUserId()))
            return false;
        boolean save = removeById(commentId);
        if (!save)
            return false;
        //更新skill相关信息
        Skill skill = skillService.getById(skillComment.getSkillId());
        String oldStar = skill.getStar();
        Integer comments = skill.getComments();
        double newStar = (Double.parseDouble(oldStar)*comments- skillComment.getStar())/(comments-1);
        if(comments - 1 == 0){
            newStar = 5;
        }
        DecimalFormat df = new DecimalFormat("#.0");
        String star = df.format(newStar);
        skill.setStar(star);
        skill.setComments(comments-1);
        boolean update = skillService.updateById(skill);
        if (!update)
            return false;
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean update(SkillCommentUpdateVO commentVO) {
        SkillComment skillComment = getById(commentVO.getId());
        Integer oldStar = skillComment.getStar();
        BeanUtils.copyProperties(commentVO, skillComment);
        boolean save = updateById(skillComment);
        if (!save){
            return false;
        } else {
            if (oldStar.equals(commentVO.getStar())) {
                return true;
            }
            //更新技能星数
            System.out.println(skillComment);
            Skill skill = skillService.getById(skillComment.getSkillId());
            Integer comments = skill.getComments();
            double newStar = (Double.parseDouble(skill.getStar())*comments-oldStar+commentVO.getStar())/(comments);
            DecimalFormat df = new DecimalFormat("#.0");
            String star = df.format(newStar);
            skill.setStar(star);
            boolean update = skillService.updateById(skill);
            if (!update)
                return false;
            return true;
        }
    }

    //根绝skillId直接全部删除
    @Override
    @Transactional(rollbackFor=Exception.class)
    public boolean removeBySkillId(String skillId){
        QueryWrapper<SkillComment> wrapper = new QueryWrapper<>();
        wrapper.eq("skill_id",skillId);
        boolean remove = remove(wrapper);
        return remove;
    }

    @Override
    public Map<String, Object> pageCommentCondition(long current, long limit, CommentQuery commentQuery) {
        //1.创建page对象
        Page<SkillComment> pageComment = new Page<>(current, limit);
        //3.构建条件
        QueryWrapper<SkillComment> wrapper = new QueryWrapper<>();
        String skillId = commentQuery.getSkillId();
        String userId = commentQuery.getUserId();
        String begin = commentQuery.getBegin();
        String end = commentQuery.getEnd();
        if (!StringUtils.isEmpty(skillId)) {
            wrapper.eq("skill_id", skillId);
        }
        if (!StringUtils.isEmpty(userId)) {
            wrapper.eq("user_id", userId);
        }
        if (!StringUtils.isEmpty(begin)) {
            //这里的column列名必须使用数据库文件中的列名
            wrapper.ge("create_date", begin);
        }
        if (!StringUtils.isEmpty(end)) {
            //这里的column列名必须使用数据库文件中的列名
            wrapper.le("create_date", end);
        }
        //调用方法实现条件分页查询(按照更新时间的先后顺序)
        wrapper.orderByDesc("update_date");
        page(pageComment, wrapper);
        long total = pageComment.getTotal();
        List<SkillComment> records = pageComment.getRecords();
        if(records == null){
            return null;
        }
        List<SkillCommentListVO> voList = new ArrayList<>();
        for (SkillComment record : records) {
            SkillCommentListVO commentVO = new SkillCommentListVO();
            BeanUtils.copyProperties(record,commentVO);
            User user = userService.getById(record.getUserId());
            UserInfo userInfo = (UserInfo) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            String meId = userInfo.getUserId();
            if(user.getId().equals(meId)){
                commentVO.setMe(true);
            }
            String nickname = user.getNickname();
            String avatar = user.getAvatar();
            commentVO.setNickname(nickname);
            commentVO.setAvatar(avatar);
            voList.add(commentVO);
        }
        Map<String,Object> map = new HashMap<>();
        map.put("total",total);
        map.put("rows",voList);
        return map;
    }


}
